package com.musicstore.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.musicstore.dao.MyBatisUtil;
import com.musicstore.dao.UserDao;
import com.musicstore.entity.User;

/**
 * Servlet implementation class Register
 */
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("UTF-8");
		String name=request.getParameter("name");
		SqlSession session =MyBatisUtil.openSession();
		UserDao userDao =session.getMapper(UserDao.class);
		User user =userDao.fetchByUsername(name);
		if (user==null) {
			out.println("true");
		}else {
			out.println("false");
		}
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		SqlSession session =MyBatisUtil.openSession();
		UserDao userDao =session.getMapper(UserDao.class);
		User user =userDao.checkLogin(name,pwd);
		
		if(user != null){
			request.setAttribute("message", user.getName());
			request.getRequestDispatcher("show.jsp").forward(request, response);
		}else {
			request.setAttribute("message", "登陆失败");
			request.getRequestDispatcher("register.jsp").forward(request, response);
		}
		
	}

}
